package com.ccx.coachsite.ui.softmgr;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.ccx.coachsite.data.SystemConst;
import com.ccx.coachsite.downloadmgr.DownloadService;
import com.ccx.coachsite.model.PageInfo;
import com.ccx.coachsite.model.ServerResult;
import com.ccx.coachsite.model.SoftTypeVO;
import com.ccx.coachsite.util.LogUtil;
import com.ccx.coachsite.util.SUtil;
import com.ccx.coachsite.util.U;
import com.ccx.coachsite.util.net.UrlParse;


public class SoftMgrUtil {
	private final static String TAG="SoftMgrUtil";
	public static long mTotalCount=0;
	
	public static ServerResult<SoftInfo> loadSoftOnline(String urlString,Context ctx) throws Exception
	{
		UrlParse parse = new UrlParse(urlString);
		urlString = parse.getUrl();
		
		HttpURLConnection conn=null;
		InputStream in = null;
		try {
			conn = getConnection(urlString);
			in=conn.getInputStream();
			
			return parseJsonToObject(in,ctx);
		} catch (MalformedURLException e) {
			throw e;
		} catch (IOException e) {
			throw e;
		} catch (Exception e){
			throw e;
		} finally{
			if(conn!=null)
				conn.disconnect();
			if(in != null)
				in.close();
		}
	}
	private static String getStringFromIn(InputStream in) {
		return getStringFromIn(in,null);
	}
	private static String getStringFromIn(InputStream in,String encode) {
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader buffer = null;
		try {
			if(in == null){
				return null;
			}
			if(encode != null){
				buffer = new BufferedReader(new InputStreamReader(in,encode));
			}else{
				buffer = new BufferedReader(new InputStreamReader(in));
			}
			while ((line = buffer.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(buffer != null)
					buffer.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	/**
	 * 通过输入流获取Json 并解析成对象集合
	 * @param in
	 * @param ctx
	 * @return
	 * @throws JSONException 
	 */
	private static ServerResult<SoftInfo> parseJsonToObject(InputStream in,
			Context ctx) throws JSONException {
		String jsonString = getStringFromIn(in);
		LogUtil.d(TAG, jsonString);
		JSONObject jsonData = new JSONObject(jsonString);
		if(jsonData.getInt("Code") != 0){
			return null;
		}
		
		JSONObject result = jsonData.getJSONObject("Result");
		ServerResult<SoftInfo> serverResult = new ServerResult<SoftInfo>();
		
		 PageInfo pageInfo = new  PageInfo();
		 pageInfo.currentPageNum = 1;
		 pageInfo.totalPages = 10;
		 
		serverResult.setPageInfo(pageInfo);
		serverResult.setResultCode(200);
		JSONArray itemList = result.getJSONArray("items");
		for(int i=0;i<itemList.length();i++){
			JSONObject item =  itemList.getJSONObject(i);
			SoftInfo softInfo=new SoftInfo();
			softInfo.setSid(item.getString("resId"));
			softInfo.setPkgName(item.getString("identifier"));
			softInfo.setAvailVersion(item.getString("versionName"));
			softInfo.setAvailVersionCode(item.getString("versionCode"));
			softInfo.setTitle(item.getString("name"));
			softInfo.setIconUrl(item.getString("icon"));
			softInfo.setDownloadUrl(item.getString("downloadUrl"));
			softInfo.setDetailUrl(item.getString("detailUrl"));
			softInfo.setSize(item.getString("size")); //文件大小，带KB，MB字串
			
			try{
				softInfo.setFileBytes(Long.parseLong(
					SUtil.getNumberStringByKey(softInfo.getDownloadUrl(), "fsize")));//文件的字节数，也是文件大小，只是字节数，不直观
			}catch (NumberFormatException e) {
				softInfo.setFileBytes(0);
			}
			softInfo.setGrade(item.getInt("star"));
			softInfo.setUpdateTime("");
			softInfo.setFilePath(getFilePath(softInfo));
			int activeStatus=DownloadService.getDownloadStatus(ctx, softInfo);//当前该的状态
			softInfo.setStatus(activeStatus);
			serverResult.itemList.add(softInfo);
		}
		
		return serverResult;
	}

	
	/**
	 * 获取网络连接
	 * @param strUrl
	 * @return
	 * @throws Exception
	 */
	public static HttpURLConnection getConnection(String strUrl) throws Exception
	{
		for(int i=0;i<2;i++)
		{
			//尝试两次连接
			try {
				URL url=new URL(strUrl);
				HttpURLConnection conn=(HttpURLConnection) url.openConnection();
				conn.setDoInput(true);
				conn.setConnectTimeout(60000);
				conn.setReadTimeout(5000);
				conn.connect();
				return conn;
			} catch(Exception e){
				if(i==1)
					throw e;
			}
		}
		return null;
	}
	
	/**
	 * 组装 软件升级的URL所带的参数
	 * @param strUrl
	 * @param ctx
	 * @return
	 */
	private static List<ParamVO> getUpgradeParams(Context ctx)
	{
		PackageManager pm=ctx.getPackageManager();
		List<PackageInfo> pkgList=pm.getInstalledPackages(0);
		
		List<ParamVO> paramList=new ArrayList<ParamVO>();
		for(PackageInfo pkgInfo:pkgList)
		{
			ApplicationInfo appInfo=pkgInfo.applicationInfo;
			if(appInfo==null)
				continue;
			
			//系统应用不进行升级，所以过滤掉
			boolean isSystemApp=U.isSystemPkg(ctx, appInfo.packageName);
			if(isSystemApp) 
				continue;
			
			String pkgName=appInfo.packageName;
			String version=null;
			version=""+pkgInfo.versionCode;
			version=version==null?"0":version;
			ParamVO param=new ParamVO();
			param.pkgName=pkgName;
			param.versionCode=version;
			paramList.add(param);
		}
		return paramList;
	}
	
	/**
	 * 获取升级软件列表
	 * @param in
	 * @return
	 * @throws Exception 
	 */
	public static List<SoftInfo> getUpgradeList(String strUrl,Context ctx) throws Exception
	{
		UrlParse parse = new UrlParse(strUrl);
		strUrl = parse.getUrl();
		
		LogUtil.d(TAG, "strUrl="+strUrl);
		
		List<SoftInfo> softList=new ArrayList<SoftInfo>();
		try {
			List<ParamVO> paramList=getUpgradeParams(ctx);
			HttpPost httpPost=new HttpPost(strUrl);
			
			StringBuffer installedSofts  = new StringBuffer();
			for(ParamVO param:paramList){
				installedSofts.append(param.pkgName+",");
				installedSofts.append(param.versionCode+";");
			}
			List<NameValuePair> params=new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("installedSofts",installedSofts.toString()));
			
			HttpEntity entity=new UrlEncodedFormEntity(params);
			httpPost.setEntity(entity);
			//提交网络请求
			HttpResponse httpResponse=new DefaultHttpClient().execute(httpPost);
			
			if(httpResponse.getStatusLine().getStatusCode()==200)//200表示成功返回
			{
				HttpEntity resEntity=httpResponse.getEntity();
				byte[] resBytes=EntityUtils.toByteArray(resEntity);
				List<SoftInfo> tempList = getUpdateList(new String(resBytes));	
				if(tempList!=null)
					softList.addAll(tempList);
			}//end if

			return softList;
		} catch (Exception e) {
			throw e;
		}//end try
	}//end getUpgradeList
	
	/**
	 * 获取升级软件列表
	 * @param jsonStr
	 * @return
	 * @throws JSONException 
	 */
	private static List<SoftInfo> getUpdateList(String jsonStr) throws JSONException{
		LogUtil.d(TAG, jsonStr);
		JSONObject jsonObj = new JSONObject(jsonStr);
		if(jsonObj == null || jsonObj.getInt("Code")!=0)
			return null;
		List<SoftInfo> softInfoList = new ArrayList<SoftInfo>();
		JSONArray resultJson = jsonObj.getJSONArray("Result");
		for(int i=0;i<resultJson.length();i++){
			JSONObject softInfoJson = resultJson.getJSONObject(i);
			SoftInfo softInfo=new SoftInfo();
			softInfo.setSid("");
			softInfo.setAvailVersion(softInfoJson.getString("versionName"));
			softInfo.setAvailVersionCode(softInfoJson.getString("versionCode"));
			softInfo.setPkgName(softInfoJson.getString("identifier"));
			softInfo.setDownloadUrl(softInfoJson.getString("downloadUrl"));
			softInfo.setSize(softInfoJson.getString("size")); //文件大小，带KB，MB字串
			softInfo.setFileBytes(0);//文件的字节数，也是文件大小，只是字节数，不直观
			try{
				softInfo.setFileBytes(Long.parseLong(SUtil.getNumberStringByKey(softInfo.getDownloadUrl(), "fsize")));
			}catch (NumberFormatException e) {
				softInfo.setFileBytes(0);
			}
			softInfo.setSid(SUtil.getNumberStringByKey(softInfo.getDownloadUrl(), "resId"));

			softInfo.setIconUrl(softInfoJson.getString("icon"));
			softInfo.setUpdateTime("");
			
			softInfo.setFilePath(getFilePath(softInfo));
			softInfoList.add(softInfo);
		}
		return softInfoList;
	}
	
	public static String getFilePath(SoftInfo softInfo){
		return SystemConst.DOWNLOAD_DIR+softInfo.getPkgName()+"-"+softInfo.getAvailVersionCode()+".apk";
	}
	
	/**
	 * 获取软件详情 根据软件sid
	 * @param context
	 * @param mItem
	 * @throws Exception 
	 */
	public static void setSoftDetail(Context context, SoftInfo softInfo) throws Exception {
		String urlString = softInfo.getDetailUrl();
		UrlParse parse = new UrlParse(urlString);
		urlString = parse.getUrl();
		
		HttpURLConnection conn=null;
		InputStream in = null;
		try {
			conn = getConnection(urlString);
			in=conn.getInputStream();
			String jsonString = getStringFromIn(in);
			JSONObject jsonData = new JSONObject(jsonString);
			if(jsonData.getInt("Code") != 0){
				return;
			}
			JSONObject jsonResult = jsonData.getJSONObject("Result");
			
			softInfo.setIntroduction(jsonResult.getString("desc"));
			
			softInfo.setAvailVersion(jsonResult.getString("version"));

			softInfo.setTitle(jsonResult.getString("resName"));
			softInfo.setIconUrl(jsonResult.getString("icon"));
			softInfo.setDownloadUrl(jsonResult.getString("downloadUrl"));
			softInfo.setSize(jsonResult.getString("size")); //文件大小，带KB，MB字串
			
			try{
				softInfo.setFileBytes(Long.parseLong(
					SUtil.getNumberStringByKey(softInfo.getDownloadUrl(), "fsize")));//文件的字节数，也是文件大小，只是字节数，不直观
			}catch (NumberFormatException e) {
				softInfo.setFileBytes(0);
			}
			
			softInfo.setGrade(jsonResult.getInt("star"));
			softInfo.setUpdateTime("");
			
			softInfo.setIntroLength(softInfo.getIntroduction().length());
			softInfo.setLanguage(jsonResult.getString("lan"));
			JSONArray snapshotsArray = jsonResult.getJSONArray("snapshots");
			if(snapshotsArray.length() > 0)
				softInfo.setPreImageUrl(jsonResult.getJSONArray("snapshots").getString(0));
			softInfo.setDownloadCount(jsonResult.getString("downloadNumber"));
			softInfo.setUpdateTime(jsonResult.getString("updateTime"));
			softInfo.setFilePath(getFilePath(softInfo));
			int activeStatus=DownloadService.getDownloadStatus(context, softInfo);//当前该的状态
			softInfo.setStatus(activeStatus);
			
		} catch (Exception e){
			throw e;
		} finally{
			if(conn!=null)
				conn.disconnect();
			if(in!=null)
				in.close();
		}
		
	}
	
	/**
	 * 获取软件详情 根据软件sid
	 * @param context
	 * @param mItem
	 * @throws Exception 
	 */
	public static SoftInfo getSoftDetail(Context context,String sSoftID, String uid) throws Exception {
		
		SoftInfo softInfo = new SoftInfo(); 
		softInfo.setSid(sSoftID);
		softInfo.setDetailUrl("http://bbx2.sj.91.com/soft/phone/detail.aspx?act=226&mt=4&pid=2&osv=1&iv=2&resId="+sSoftID);
		String urlString = softInfo.getDetailUrl();
		UrlParse parse = new UrlParse(urlString);
		urlString = parse.getUrl();
		
		HttpURLConnection conn=null;
		InputStream in = null;
		try {
			conn = getConnection(urlString);
			in=conn.getInputStream();
			String jsonString = getStringFromIn(in);
			JSONObject jsonData = new JSONObject(jsonString);
			if(jsonData.getInt("Code") != 0){
				return null;
			}
			JSONObject jsonResult = jsonData.getJSONObject("Result");
			
			softInfo.setIntroduction(jsonResult.getString("desc"));
			
			softInfo.setAvailVersion(jsonResult.getString("version"));

			softInfo.setTitle(jsonResult.getString("resName"));
			softInfo.setIconUrl(jsonResult.getString("icon"));
			softInfo.setDownloadUrl(jsonResult.getString("downloadUrl"));
			softInfo.setSize(jsonResult.getString("size")); //文件大小，带KB，MB字串
			
			try{
				softInfo.setFileBytes(Long.parseLong(
					SUtil.getNumberStringByKey(softInfo.getDownloadUrl(), "fsize")));//文件的字节数，也是文件大小，只是字节数，不直观
			}catch (NumberFormatException e) {
				softInfo.setFileBytes(0);
			}
			
			softInfo.setGrade(jsonResult.getInt("star"));
			softInfo.setUpdateTime("");
			
			softInfo.setIntroLength(softInfo.getIntroduction().length());
			softInfo.setLanguage(jsonResult.getString("lan"));
			JSONArray snapshotsArray = jsonResult.getJSONArray("snapshots");
			if(snapshotsArray.length() > 0)
				softInfo.setPreImageUrl(jsonResult.getJSONArray("snapshots").getString(0));
			softInfo.setDownloadCount(jsonResult.getString("downloadNumber"));
			softInfo.setUpdateTime(jsonResult.getString("updateTime"));
			softInfo.setFilePath(getFilePath(softInfo));
			int activeStatus=DownloadService.getDownloadStatus(context, softInfo);//当前该的状态
			softInfo.setStatus(activeStatus);
			
		} catch (Exception e){
			throw e;
		} finally{
			if(conn!=null)
				conn.disconnect();
			if(in!=null)
				in.close();
		}
		
		return softInfo;
	}	
	
	/**
	 * 获取软件介绍的全部内容
	 * @param strUrl
	 * @param ctx
	 * @return
	 * @throws Exception 
	 */
	public static String getAllIntroduction(String strUrl,Context ctx) throws Exception
	{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = null;
		Document doc = null;
		InputStream in=null;
		HttpURLConnection conn=null;
		try {
			conn=getConnection(strUrl);
			in=conn.getInputStream();
			builder = factory.newDocumentBuilder();
			doc = builder.parse(in);
			//根节点<result>
			Element rootElement = doc.getDocumentElement();
			//<item>结节
			Element itemEL =(Element) rootElement.getElementsByTagName("item").item(0);
			
			// <item>下的所有子结点
			
			//软件介绍的全部内容
			Node allIntroNode=itemEL.getElementsByTagName("desc").item(0);
			
			String res=allIntroNode.getFirstChild()==null?null:allIntroNode.getFirstChild().getNodeValue();
			return res;
		} catch (Exception e) {
			throw e;
		}finally{
			
			try {
				if(in!=null)
					in.close();
				if(conn!=null)
					conn.disconnect();
			} catch (Exception e2) {
				LogUtil.e(TAG, e2.getMessage());
			}
				
		}
	} //end getAllIntroduction
	
	/**
	 * 获取软件类别列表
	 * @param strUrl
	 * @param ctx
	 * @return
	 * @throws Exception
	 */
	public static List<SoftTypeVO> getSoftTypeList(String strUrl) throws Exception
	{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = null;
		Document doc = null;
		InputStream in=null;
		HttpURLConnection conn=null;
		try {
			conn=getConnection(strUrl);
			in=conn.getInputStream();
			builder = factory.newDocumentBuilder();
			doc = builder.parse(in);
			//根节点<result>
			Element rootElement = doc.getDocumentElement();
			NodeList itemList=rootElement.getElementsByTagName("item");
			int len=itemList.getLength();
			List<SoftTypeVO> typList=new ArrayList<SoftTypeVO>(len);
			for(int i=0;i<len;i++)
			{
				//<item>结节
				Element itemEL =(Element) itemList.item(i);
				
				// <item>下的所有子结点
				//ID
				Node idNode=itemEL.getElementsByTagName("cateId").item(0);
				//类别名称
				Node cateNameNode=itemEL.getElementsByTagName("cateName").item(0);
				//类型下的软件数量
				Node softCountNode=itemEL.getElementsByTagName("softCount").item(0);
				
				String id=idNode.getFirstChild()==null?"":idNode.getFirstChild().getNodeValue();
				String cateName=cateNameNode.getFirstChild()==null?"":cateNameNode.getFirstChild().getNodeValue();
				String softCount=softCountNode.getFirstChild()==null?"0":softCountNode.getFirstChild().getNodeValue();
				long lSoftCount=Long.parseLong(softCount);
				SoftTypeVO typeVO=new SoftTypeVO();
				typeVO.setId(id);
				typeVO.setTitle(cateName);
				typeVO.setSoftCount(lSoftCount);
				typList.add(typeVO);
			}
			return typList;
		} catch (Exception e) {
			throw e;
		}finally{
			
			try {
				if(in!=null)
					in.close();
				if(conn!=null)
					conn.disconnect();
			} catch (Exception e2) {
				LogUtil.e(TAG, e2.getMessage());
			}
				
		}
	} //end getAllIntroduction

	/*-------------------------------------------------内部类--------------------------------------------------------------*/
	private static class ParamVO
	{
		public String pkgName;
		public String versionCode;
	}
}





















